package com.hcc.gateway.netty.server;

import com.hcc.gateway.netty.config.GatewayConfig;
import com.hcc.gateway.netty.handler.GatewayServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * HttpServerInitializer
 *
 * @author hushengjun
 * @date 2020-09-07-007
 */
public class GatewayServerInitializer extends ChannelInitializer<SocketChannel> {

    private final GatewayConfig config;

    public GatewayServerInitializer(GatewayConfig config) {
        this.config = config;

        // TODO 初始化路由信息
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // 向管道加入处理器
        ChannelPipeline pipeline = ch.pipeline();

        // 编解码处理，对象必须实现序列化接口
        pipeline.addLast(new HttpServerCodec());
        Integer maxContentLength = config.getMaxContentLength();
        if (maxContentLength == null) {
            maxContentLength = 10 * 1024 * 1024;
        }
        pipeline.addLast(new HttpObjectAggregator(maxContentLength));
        // 读写心跳处理
        pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
        // 业务处理
        pipeline.addLast(new GatewayServerHandler(config));
    }

}
